from iamadb import iamadb, thread, author, conversation
from boe2.reddit import *

reddit = client.client()
articles = reddit.getSubReddit("iama", limit=20)
comments = {}
conversations = {}

def addComments(commentlist):
	for comment in commentlist:
		comments[comment.fullname()] = comment
		addComments(comment.replies)
        
def createConversation(comment):
    conv = conversation()
    conv.thread = thr.id
    conv.q_id = comment.parent_id
    conv.q_author = comments[comment.parent_id].author
    conv.q_body = comments[comment.parent_id].body
    conv.q_posted = comments[comment.parent_id].created
    conv.a_id = comment.fullname()
    conv.a_author = comment.author
    conv.a_body = comment.body
    conv.a_posted = comment.created
    conv.save(db)

with iamadb("iama.sqlite") as db:
    for article in articles.data:
        if "request" not in article.title.lower():
            thr = thread()
            thr.id = article.fullname()
            thr.title = article.title
            thr.author = article.author
            thr.body = article.selftext
            thr.posted = article.created
            thr.last_update = article.edited
            thr.url = article.permalink
            thr.save(db)
            print("Saving comments for " + thr.id + "...")
            commentlist = reddit.getComments(article.permalink)
            addComments(commentlist)
            for commentid, comment in comments.items():
                if comment.author == thr.author and comment.parent_id is not None and not comment.parent_id.startswith("t3_"):
                    createConversation(comment)
print("Done!")
